package cn.com.transfer.params;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;

/**
 * Created by Administrator on 2015/4/3.
 */
public abstract class Params {
    private Logger logger = LoggerFactory.getLogger(Params.class);

    @Override
    public String toString() {
        StringBuffer sb = new StringBuffer();
        try {
            Field[] fields = this.getClass().getFields();
            ParamLength pl;
            for (int i = 0; i < fields.length; i++) {
                for (Field field : fields) {
                    if (!field.isAnnotationPresent(ParamLength.class)) continue;
                    pl = field.getAnnotation(ParamLength.class);

                    if (pl.order() == i + 1) {
                        field.setAccessible(true);
                        String value = (String) field.get(this);
                        if (value == null) continue;

                        value = new String(value.getBytes("GB18030"), "ISO-8859-1");

                        //左对齐补空格
                        value = String.format("%-" + pl.length() + "s", value);

                        sb.append(new String(value.getBytes("ISO-8859-1"), "GB18030"));
                        break;
                    }
                }
            }
        } catch (Exception e) {
            logger.error("error to turn params to string", e);
        }
        return sb.toString();
    }
}
